<template>
  <div class="database-service h-full flex">
    <!-- 连接浏览器 -->
    <div class="connection-browser flex-shrink-0 w-80 bg-white border-r border-gray-200">
      <ConnectionBrowser />
    </div>

    <!-- 标签页内容区域 -->
    <div class="tab-content-area flex-1 flex flex-col bg-gray-50">
      <!-- 标签页头部 -->
      <div class="tab-header bg-white border-b border-gray-200">
        <TabHeader />
      </div>

      <!-- 标签页内容 -->
      <div class="tab-content flex-1 overflow-hidden">
        <TabContent />
      </div>
    </div>

    <!-- 导入数据对话框 -->
    <ImportDataDialog
      v-if="showImportDialog && importDialogConfig && isImportConfigValid"
      :visible="showImportDialog"
      @update:visible="showImportDialog = $event"
      :connection-id="importDialogConfig?.connectionId || ''"
      :connection-type="importDialogConfig?.connectionType || ''"
      :database-name="importDialogConfig?.database || ''"
      :table-name="importDialogConfig?.table || ''"
      :table-columns="importDialogConfig?.columns || []"
      @success="handleImportSuccess"
      @close="handleImportDialogClose"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useAppStore } from '@/stores'
import ConnectionBrowser from '@/components/database/ConnectionBrowser.vue'
import TabHeader from '@/components/database/TabHeader.vue'
import TabContent from '@/components/database/TabContent.vue'
import ImportDataDialog from '@/components/database/ImportDataDialog.vue'

const appStore = useAppStore()
const showImportDialog = ref(false)
const importDialogConfig = ref(null)

// 检查导入配置是否有效
const isImportConfigValid = computed(() => {
  if (!importDialogConfig.value) return false
  
  const config = importDialogConfig.value
  const isValid = !!(
    config.connectionId && 
    config.database && 
    config.table
  )
  
  if (!isValid) {
    console.error('Invalid import dialog configuration:', config)
  }
  
  return isValid
})

// 监听显示导入对话框事件
const handleShowImportDialog = (event) => {
  if (!event || !event.data) {
    console.error('Invalid import dialog event:', event)
    return
  }
  
  console.log('Received import dialog config:', event.data)
  
  // 处理数据可能是数组的情况（从后端接收的数据可能被包装在数组中）
  const configData = Array.isArray(event.data) ? event.data[0] : event.data
  
  if (!configData) {
    console.error('Import dialog config is empty')
    return
  }
  
  // 验证必要字段
  const requiredFields = ['connectionId', 'database', 'table']
  const missingFields = requiredFields.filter(field => !configData[field])
  
  if (missingFields.length > 0) {
    console.error(`Import dialog missing required fields: ${missingFields.join(', ')}`)
    return
  }
  
  importDialogConfig.value = configData
  showImportDialog.value = true
}

// 处理导入成功
const handleImportSuccess = (result) => {
  // 发送刷新表数据事件
  import('@wailsio/runtime').then(({ Events }) => {
    Events.Emit('refresh:table-data', {
      connectionId: importDialogConfig.value.connectionId,
      database: importDialogConfig.value.database,
      table: importDialogConfig.value.table
    })
  }).catch(error => {
    console.error('Failed to emit refresh event:', error)
  })
}

// 处理导入对话框关闭
const handleImportDialogClose = () => {
  showImportDialog.value = false
  // 延迟清空配置，以避免在对话框关闭动画过程中组件消失
  setTimeout(() => {
    importDialogConfig.value = null
  }, 300)
}

onMounted(() => {
  // 设置当前激活的服务
  appStore.setActiveService('database')

  // 注册导入对话框事件监听
  import('@wailsio/runtime').then(({ Events }) => {
    Events.On('show:import-dialog', handleShowImportDialog)
  }).catch(error => {
    console.error('Failed to register event listener:', error)
  })
})

onUnmounted(() => {
  // 移除事件监听
  import('@wailsio/runtime').then(({ Events }) => {
    Events.Off('show:import-dialog')
  }).catch(error => {
    console.error('Failed to remove event listener:', error)
  })
})
</script>

<style scoped>
.database-service {
  min-height: 0; /* 重要：允许flex子元素收缩 */
}

.connection-browser {
  min-width: 280px;
  max-width: 500px;
  resize: horizontal;
  overflow: auto;
}

.tab-content-area {
  min-width: 0; /* 重要：允许flex子元素收缩 */
}

.tab-header {
  height: 48px;
  flex-shrink: 0;
}

.tab-content {
  min-height: 0; /* 重要：允许flex子元素收缩 */
}

/* 调整大小手柄样式 */
.connection-browser::-webkit-resizer {
  background: #e5e7eb;
  border-radius: 2px;
}
</style> 